<?php

/**
 * 默认控制器
 */
class Controller_Wap extends Controller_Abstract
{
	private $leftchar = '{';
	private $rightchar = '}';
	function _response($data)
	{
		exit(iconv('UTF8','GBK',$data));
	}
	function actioncall()
	{
	}
	/**
	 * QQ充值ID
	 */
	function actionqqpayid()
	{
		$payid = trim($this->_context->payid);
		$mobile = trim($this->_context->mobile);
		if (strlen($payid)<2 || strlen($mobile)<2 )
		{
			$this->_response('ERR:数据不完整');
		}
		$isNew = Acctuser::find('acctname = ?',$mobile)->getCount('id');
		if ($isNew>0)
		{
			$this->_response('ERR:快捷开户只能开卡不能给现有用户充值！');
			
		}
		$card = Vouchercard::find('payid = ? and enable = 1 and vouchered = 0',$payid)->getOne();
		if (!$card->id())
		{
			$this->_response('ERR:无快捷卡可以使用!');
		}
		$cardid = $card->cardname;
		$cardpwd = $card->password;
		if(!Helper_Param::_call($mobile))
		{
			$this->_response('ERR:手机号码格式不正确');
		}else{
			$flag = Acctuser::use_card($mobile, $cardid, $cardpwd,'','');
			if($flag === true)
			{
				$this->_response($card->password);
			}else{
				$this->_response('ERR:失败:'.$flag);
			}
		
		}
	}
	function actionureg()
	{
		$result = '';
			$union = trim($this->_context->union);
			
		if ($this->_context->isPOST())
		{
			$unionUser = Acctuser::checkAcctname($union);
			
			if ($union == '' || !$unionUser->id())
			{
				exit('没有找到推荐用户');
				die;
			}
			$mobile = trim($this->_context->mobile);
			$pwd = Helper_Common::get_rnd(0,6);
			
			
			$acctwap = Acctwapset::find('acctid = ?',$unionUser->agent_id)->getOne();
			if (!Helper_Param::_call($mobile))
			{
				$result = '手机号码格式不正确';
			}else if ($acctwap->open_reg == 1)
			{
				$result = '代理未打开注册';
			}else{
				$has = Acctuser::checkAcctname($mobile);
				if ($has->id())
				{
					$result = '手机已经开通';
				}else{
					$acctuser = new Acctuser();
					$acctuser->agent_id = $unionUser->agent_id;
					$acctuser->admin_id = $unionUser->admin_id;
					$acctuser->unionacctname = $unionUser->acctname;	
					$acctuser->acctname = $mobile;
					$acctuser->password = $pwd;
					$acctuser->balance = $acctwap->safe_money;
					$acctuser->activedate = date('Y-m-d');
					$acctuser->expireddays = $acctwap->expireddays;
					$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->activedate} + {$acctuser->expireddays} day"));
					//$acctuser->bindexten_type = 0;
					//$acctuser->expireddays = $card->expireddays;
					$acctuser->rategroupid = $acctwap->rategroupid;
					$acctuser->rategroupid_acall = $acctwap->rategroupid_acall;
					$acctuser->limitbalance = 0;
					try {
						$acctuser->save(0,'create');
						$bind = new Userbindtel();
						$bind->admin_id = $acctuser->admin_id;
						$bind->agent_id = $acctuser->agent_id;
						$bind->acctname = $mobile;
						$bind->bindtel = $mobile;
						$bind->save(0,'create');//添加绑定号码
						//return true;
					} catch (Exception $e) {
			
					}
					$result = '注册成功';
					$sql = "call fscall.httppost('{$mobile}','','',1)";
					QDB::getConn()->execute($sql);
					QDB::getConn()->close();
				}
			
			}
		}else{
			
		}
		$this->_view['union'] = $union;
		$this->_view['result'] = $result;
	}
	/**
	 * 充值ID充值
	 */
	function actionpayid()
	{
		if($this->_context->isPOST())
		{
			if (!Helper_Ckcode::check($this->_context->codeOK))
			{
				return $this->_redirectMessage('错误', '验证码错误', url('wap/payid'));
			}else{
				$payid = trim($this->_context->payid);
				$mobile = trim($this->_context->adphone);
				$unionuser = trim($this->_context->unionuser);
				if (strlen($payid)<2 || strlen($mobile)<2 )
				{
					return $this->_redirectMessage('错误', '必须输入数据', url('wap/payid'));
					exit;
				}
				$isNew = Acctuser::find('acctname = ?',$mobile)->getCount('id');
				if ($isNew>0)
				{
					return $this->_redirectMessage('错误', '快捷开户只能开卡不能给现有用户充值！', url('wap/payid'));
					exit;
				}
				$card = Vouchercard::find('payid = ? and enable = 1 and vouchered = 0',$payid)->getOne();
				if (!$card->id())
				{
					return $this->_redirectMessage('错误', '无快捷卡可以使用!', url('wap/payid'));
					exit;
				}
				$cardid = $card->cardname;
				$cardpwd = $card->password;
				if(!Helper_Param::_call($mobile))
				{
					return $this->_redirectMessage('错误', '手机号码格式不正确', url('wap/payid'));
					exit;
				}else{
					$flag = Acctuser::use_card($mobile, $cardid, $cardpwd,'',$unionuser);
					if($flag === true)
					{
						//$card = Vouchercard::find('cardname = ? and password = ?',$cardid,$cardpwd)->setColumns('id,balance')->getOne();
						$result = $card->balance;
						return $this->_redirectMessage('充值成功', '开户成功,余额:'.$result, url('wap/payid'));
						exit;
					}else{
						$result = $flag;
						return $this->_redirectMessage('错误', '失败:'.$result, url('wap/payid'));
						exit;
					}
		
				}
		
			}
				
		}else{
				
		}
	}
	
	function actionpay()
	{
		Q::changeIni('runtime_response_header',false);
		//header("Content-type: text/vnd.wap.wml");
		header("Content-type: text/html; charset=utf-8");
		echo '<?xml version="1.0" encoding="UTF-8"?>';
			
		if($this->_context->isPOST())
		{
// 			if (!Helper_Ckcode::check($this->_context->codeOK))
// 			{
// 				$result = "验证码错误";
// 				exit($result);
// 			}else
			{
				$mobile = $this->_context->adphone;
				$cardid = $this->_context->cardid;
				$cardpwd = $this->_context->cardpass;
				
				if(!Helper_Param::_call($mobile))
				{
					$err = ('手机号码格式不正确1'); //手机号码格式不正确
				}else{
					//$user = Acctuser::checkAcctname($mobile);
					//if(!$user->id())
					//{
					//	$result = 'ERR2'; //不存在此绑定号码
					//}else{
					$flag = Acctuser::use_card($mobile, $cardid, $cardpwd);
					if($flag === true)
					{
						$card = Vouchercard::find('cardname = ? and password = ?',$cardid,$cardpwd)->setColumns('id,balance')->getOne();
						$result = $card->balance;
						$err = ('成功充值:'.$result);
					}else{
						$result = $flag;
						$err = ('失败:'.$result);
					}
				
				}
				
			}
			
		}else{
			
		}
		$this->_view['err'] = $err;
	}
	function actiontt()
	{
		header("Content-type: text/html; charset=utf-8");
		if($this->_context->isPOST())
		{
			if (!Helper_Ckcode::check($this->_context->codeOK))
			{
				$result = "验证码错误";
				exit($result);
			}else
			{
				$mobile = $this->_context->adphone;
				$cardid = $this->_context->cardid;
				$cardpwd = $this->_context->cardpass;
				if(!Helper_Param::_call($mobile))
				{
					exit('手机号码格式不正确1'); //手机号码格式不正确
				}else{
					//$user = Acctuser::checkAcctname($mobile);
					//if(!$user->id())
					//{
					//	$result = 'ERR2'; //不存在此绑定号码
					//}else{
					$flag = Acctuser::use_card($mobile, $cardid, $cardpwd);
					if($flag === true)
					{
						$card = Vouchercard::find('cardname = ? and password = ?',$cardid,$cardpwd)->setColumns('id,balance')->getOne();
						$result = $card->balance;
						exit('成功充值:'.$result);
					}else{
						$result = $flag;
						exit('失败:'.$result);
					}
		
				}
		
			}
				
		}else{
				
		}
	}
	function actionttbalance()
	{
		$result = '';
		$mobile = $this->_context->post('mobile');
		if ($mobile)
		{
			if (!Helper_Param::_phone($mobile))
			{
				$result = sprintf('%f',0);
			}else
			{
				$user = Acctuser::checkAcctname($mobile);
				//$bind = Userbindtel::find('bindtel = ?',$mobile)->setColumns('id,acctname')->getOne();
				if(!$user->id() )
				{
					$res = sprintf('%f',0);
				}else{
					$res = sprintf('%f',isset($user->balance)?$user->balance:0);
				}
			}
			//exit('您的余额为:'.$result);
			$result.= '您的余额为:'.$res;
			
		}
		$this->_view['result'] =$result;
	}
	
	function actionttlogin()
	{
		$type = intval($this->_context->type);
		$this->_view['type'] = $type;
		if ($this->_context->isPOST() )
		{
			$username = $this->_context->post('username');
			$userpass = $this->_context->post('userpass');
			$rnd  = $this->_context->post('rndcode');
			
			if (!Helper_Ckcode::check($rnd)){
				return $this->_redirectMessage('登陆失败', '验证码错误', url('login/index'));
				exit;
			}
				$flag = Acct::check_user_pass($username,$userpass);
				if ($flag == false)
				{
					return $this->_redirectMessage('登陆失败', '账号密码错误', url('wap/ttlogin'));
				}else{
					$filename = Q::ini('app_config/ROOT_DIR').'/config/power.yaml';
						$set = Helper_YAML::load($filename);
						$power = $set['power'];
					if (isset($power[$_SESSION['acct']['acclevel']]))
					{
						$user_power = $power[$_SESSION['acct']['acclevel']];
						foreach ($user_power as $k=>$v)
						{
							$user_power[$k] = explode(',', $v);
						}
						$_SESSION['power'] = $user_power;
						Syslog::logs('登陆成功');
					}else
					{
						return $this->_redirectMessage('登陆失败', '对不起,您当前的用户组没有任何权限', url('wap/ttlogin'));
						exit();
					}
					return $this->_redirectMessage('登陆成功', '帐号登录成功', url('wap/ttindex',array('type'=>$type)));
					//header('location:'.url('login/main'));
				}
			
				
		}
	}
	function actionttindex()
	{
		if (!isset($_SESSION['acct']) )
		{
			echo $this->_redirectMessage('错误', '您没有登陆', url('admin::login'))->execute();
			exit();
		}
		$type = intval($this->_context->type);
		$data = Cbnumlist::find('agent_id = ?',$type)->order('sipcode asc')->getAll();
		$this->_view['data'] = $data;
	}
	
	function actionreg()
	{
		$aid = intval($this->_context->aid);
		$uid = intval($this->_context->uid);
		$result='';
		if ($aid<0)
		{
			exit('ERR');
		}
		
		if ($this->_context->isPOST())
		{

			$mobile = trim($this->_context->mobile);
			$pwd = trim($this->_context->pwd);
			$acct = Acct::find('id = ?',$aid)->getOne();
			if (!$acct->id())
			{
				exit('没有找到代理数据');
				die;
			}
			
			$acctwap = Acctwapset::find('acctid = ?',$aid)->getOne();
			
			if (!Helper_Param::_call($mobile))
			{
				$result = '手机号码格式不正确';
			}else if ($acctwap->open_reg == 1)
			{
				$result = '代理未打开注册';
			}else{
				$has = Acctuser::checkAcctname($mobile);
				if ($has->id())
				{
					$result = '手机已经开通';
				}else{
					$acctuser = new Acctuser();
					$acctuser->agent_id = $acct->id;
					$acctuser->admin_id = $acct->admin_id;
						
					$acctuser->acctname = $mobile;
					$acctuser->password = $pwd;
					$acctuser->balance = $acctwap->safe_money;
					$acctuser->activedate = date('Y-m-d');
					$acctuser->expireddays = $acctwap->expireddays;
					$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->activedate} + {$acctuser->expireddays} day"));
					//$acctuser->bindexten_type = 0;
					//$acctuser->expireddays = $card->expireddays;
					$acctuser->rategroupid = $acctwap->rategroupid;
					$acctuser->rategroupid_acall = $acctwap->rategroupid_acall;
					$acctuser->limitbalance = 0;
					try {
						$acctuser->save(0,'create');
						$bind = new Userbindtel();
						$bind->admin_id = $acctuser->admin_id;
						$bind->agent_id = $acctuser->agent_id;
						$bind->acctname = $mobile;
						$bind->bindtel = $mobile;
						$bind->save(0,'create');//添加绑定号码
						//return true;
					} catch (Exception $e) {
			
					}
					$result = '注册成功';
				}
			
			}
		}else{
			$this->_view['aid'] = $aid;
			$this->_view['uid'] = $uid;
			
		}
		$this->_view['result'] = $result;
			
	}
	/**
	 * 
	 * Enter description here ...
	 */
	function actionshop()
	{
		$mobile = trim($this->_context->mobile);
		$user = Acctuser::checkAcctname($mobile);
		$host = '';
		if($user->id())
		{
		    $acctwap = Acctwapset::find('acctid = ?',$user->agent_id)->getOne();
		    if($acctwap->id())
		    {
		        $host = $acctwap->productdomain;
		        $host = str_replace('http://', '', $host);
		    }
		    if($host == '')$host='218.246.196.88';
		    $requestHost = $_SERVER['HTTP_HOST'];
		    if ($requestHost != $host)
		    {
		        header('Location: http://'.$host.'/wap/shop/mobile/'.$mobile);
		        exit;
		    }
			$product = Acctproduct::find('agent_id = ? and admin_id = ?',$user->agent_id,$user->admin_id)->getAll();
			$this->_view['data'] = $product;
		}else{
			exit('请先登录');
		}
	}
	
	function actionfindpwd()
	{
		$result = '';
		if($this->_context->isPOST())
		{
			$mobile = Helper_Common::trim($this->_context->mobile);
			$rnd  = $this->_context->post('codeOK');
			
			if (!Helper_Ckcode::check($rnd)){
					
				$result=('验证码错误');
				exit($result);
			}
			$acctuser = Acctuser::checkAcctname($mobile);
			if($acctuser->id())
			{
				$oparg = $acctuser->password;
				$max = QDB::getConn('fscall')->execute("SELECT COUNT(id) as num FROM fscall.outcall_cc WHERE acct = '{$acctuser->acctname}' AND created>='".date('Y-m-d')."'")->fetchOne();
				if(intval($max)>3)
				{
					$result=('对不起,今天之内只能查询3次');
				}else{
					QDB::getConn('fscall')->execute("INSERT INTO fscall.outcall_cc(acct,caller,oparg) VALUES('{$acctuser->acctname}','{$acctuser->acctname}','{$oparg}')");
					$result=('请求成功,请注意接听电话,接听过程中,可按1号键重复收听');
				}
			}else{
				$result=('账号不存在');
			}
		}
		$this->_view['result'] = $result;
		
	}
	function actionPhonePay()
	{
		$acctname = Helper_Common::trim($this->_context->acctname);
		$acctuser = Acctuser::find('acctname = ?',$acctname)->getOne();
		if($acctuser->id())
		{
			if( ($acctuser->agent->smsurl  && $acctuser->agent->smsflag && $acctuser->agent->adminsms) || $acctuser->agent->smstype == 2 )
			{
				$lastpay = Voucherlog::find('voucher_acctname = ?',$acctname)->setColumns('id,voucher_balance')->order('id desc')->getOne();
					
				if($acctuser->agent->smstype == 2)
				{
					if($lastpay->id())
					{
						$oparg = sprintf("%s-%s-%s",Acctuser::formatBlance($lastpay->voucher_balance),$acctuser->password,Acctuser::formatBlance($acctuser->balance));
						$outnewuser =array(
								'acct'=>Helper_Common::trim($acctuser->acctname),
								'caller'=>Helper_Common::trim($acctuser->acctname),
								'oparg'=>$oparg,
								'created'=>date('Y-m-d H:i:s'),
								'type'=>1,
						);
						$obj = new outcall($outnewuser);
						$obj->save(0,'create');
					}
						
				}else{
					$yu = $acctuser->balance ;
					if($acctuser->agent->smstype == 0)
					{
						$defaultstr = "手机{$acctuser->acctname}本次充值金额为{$lastpay->voucher_balance}，余额{$yu}密码{$acctuser->password}.";
						$msg = $defaultstr.$acctuser->agent->smsmsg.$acctuser->agent->smssign;
						$msgmonye = 0;
					}else{
						//$defaultstr = "({$acctuser->acctname})充值{$card->balance}元,余额{$yu},密码{$acctuser->password}。";
						$msg = $acctuser->agent->smsmsg.$acctuser->agent->smssign;
						$msgmonye = 0.05;
					}
						
					$msg = str_replace('%balance%', $lastpay->voucher_balance, $msg);
					//$msg = str_replace('%exptime%', $card->expireddays, $msg);
					$msg = str_replace('%phone%', $acctuser->acctname, $msg);
					$msg = str_replace('%money%', $yu, $msg);
					$msg = str_replace('%password%', $acctuser->password, $msg);
					$msglength = mb_strlen($msg,'UTF-8');
					#$msg = iconv("UTF-8","GB2312",$msg);
					$msg = urlencode($msg);
					$url = str_replace('%m%', $acctname, $acctuser->agent->smsurl);
					$url = str_replace('%s%', $msg, $url);
						
					//$url = sprintf($acctuser->agent->smsurl,$acctname,$msg);
					//dump($url);die;
					$result = Helper_Common::cget($url);
					QLog::log('smssend:'.$url.'|'.$result);
					$result = iconv("GB2312","UTF-8",$result);
					QDB::getConn()->execute("call smscost({$acctuser->agent->id},$msgmonye)");
						
				}				
			}
			//
		}
	}
}
